<?php

namespace app\beautiful\model\setting;

use app\beautiful\model\member\MemberModel;
use app\cash\model\CartModel;
use app\cash\model\CashJointTableModel;
use app\cash\model\CashSettleInfoModel;
use app\cash\model\OpenTableModel;
use app\common\helper\open\OpenPlatformMiniappHelper;
use app\common\model\CommonModel;
use app\stores\model\order\GoodsOrderModel;
use think\facade\Db;


class TableNumberModel extends CommonModel{

    protected  $name = 'beautiful_table_number';

    protected  $pk   = 'id';

    public static function info($where){
        $info = self::where(['is_delete'=>0])
            ->when(isset($where['id']),function ($query) use ($where){
                $query->where(['id'=>$where['id']]);
            })
            ->when(isset($where['shop_id']),function ($query) use ($where){
                $query->where(['shop_id'=>$where['shop_id']]);
            })
            ->when(isset($where['is_effect']),function ($query) use ($where){
                $query->where(['is_effect'=>$where['is_effect']]);
            })
            ->field("*")
            ->find();
        return $info;
    }
    public static function list($where,$order,$page=1,$limit=10){
        $query = Db::name('beautiful_table_number')->alias('a')
            ->join('beautiful_region b','a.region_id=b.id')
            ->where(['a.is_delete'=>0])
            ->when(!empty($where['region_id']),function ($query) use ($where){
                $query->where(['a.region_id'=>$where['region_id']]);
            })
            ->when(isset($where['shop_id']),function ($query) use ($where){
                $query->where(['a.shop_id'=>$where['shop_id']]);
            })
            ->when(!empty($where['name']),function ($query) use ($where){
                $query->where('a.name','like','%'.$where['name'].'%');
            })
            ->when(isset($where['is_effect']),function ($query) use ($where){
                $query->where(['a.is_effect'=>$where['is_effect']]);
            })
            ->when(isset($where['id']),function ($query) use ($where){
                $query->where(['a.id'=>$where['id']]);
            })
            ->when(isset($where['table_number_ids']),function ($query) use ($where){
                $query->whereIn('a.id',$where['table_number_ids']);
            })
            ->when(isset($where['not_table_number_ids']),function ($query) use ($where){
                $query->whereNotIn('a.id',$where['not_table_number_ids']);
            })
            ->when(isset($where['type']) && $where['type']==1,function ($query) use ($where){
                $query->whereNotIn('a.id',$where['open_table_number_ids']);
            })
            ->when(isset($where['type']) && $where['type']==2,function ($query) use ($where){
                $query->whereIn('a.id',$where['open_table_number_ids']);
            })
            ->field("a.*,b.name as region_name");
        $count=$query->count();
        $list=$query->order($order)
            ->limit($limit)->page($page)
            ->select()
            ->toArray();
        if($list){
            foreach ($list as $k=>$v){
                $cart_where = $t_cart_where = [];
                $ot = OpenTableModel::getById(['shop_id'=>$v['shop_id'],'table_number_id'=>$v['id'],'status'=>0]);
                if($ot){
                    //是否已生成订单
                    $cart_where[] = ['shop_id','=',$v['shop_id']];
                    $cart_where[] = ['table_number_id','=',$v['id']];
                    $cart_where[] = ['origin_type','=',2];
                    $cart_where[] = ['is_delete','=',0];
                    $cart_where[] = ['order_id','>',0];
                    $cart_order = CartModel::getCart($cart_where);

                    $pay_money = $un_pay_money = $youhui_price = 0;
                    if($cart_order){
                        $order = GoodsOrderModel::where(['order_id'=>$cart_order['order_id'],'shop_id'=>$v['shop_id'],'is_delete'=>0])->find();
                        if($order){
                            //已付
                            $total_pay_money = CashSettleInfoModel::where(['order_id'=>$cart_order['order_id'],'shop_id'=>$v['shop_id'],'info_type'=>1,'is_delete'=>0])->sum('money');
                            $refund_money = CashSettleInfoModel::where(['order_id'=>$cart_order['order_id'],'shop_id'=>$v['shop_id'],'info_type'=>1,'is_delete'=>0])->sum('refund_money');
                            $pay_money = $total_pay_money - $refund_money;

                            //优惠
                            $youhui_price= CashSettleInfoModel::where(['order_id'=>$cart_order['order_id'],'shop_id'=>$v['shop_id'],'info_type'=>2,'is_delete'=>0])->sum('money');
                            $pay_money = sprintf("%.2f",$pay_money);
                            $un_pay_money = sprintf("%.2f",$order['need_pay'] - $pay_money - $youhui_price);
                        }

                    }else{
                        $member_id = $ot['member_id'];
                        if($member_id){
                            $member_model = new MemberModel();
                            $member = $member_model->getById(['member_id'=>$member_id]);
                        }else{
                            $member = [];
                        }
                        $t_cart_where['is_fit'] = $member_id>0?0:1;
                        $t_cart_where['service_type'] = 1;
                        $t_cart_where['table_number_id'] = $v['id'];
                        $t_cart_where['member_id'] = $member_id;
                        $t_cart_where['origin_type'] = 2;
                        $t_cart_where['shop_id'] = $v['shop_id'];
                        $field = 'c.*,g.cover_img,g.origin_type,g.name,g.type,g.discount_detail,g.crossed_price,g.crossed_price,g.max_num,g.start_sales_num,g.vip_discount_type,g.cover_img,g.quota,
        g.status,g.is_vip_discount,d.group_detail_name as unit_name';
                        $return = CartModel::getCashCartlist($member,$t_cart_where,[],0,0,$field);
                        $pay_money = $return['total_price'];
                    }
                    //联台和并台
                    //是否是主桌台
                    $master = CashJointTableModel::info(['shop_id'=>$v['shop_id'],'master_table_number_id'=>$v['id'],'is_delete'=>0,'status'=>0]);
                    if($master){
                        $joint_name = '主';
                        $joint_num = $master['num'];
                        $joint_type = $master['type'];
                    }
                    //次桌台
                    $next = CashJointTableModel::info(['shop_id'=>$v['shop_id'],'table_number_id'=>$v['id'],'is_delete'=>0,'status'=>0]);
                    if($next){
                        $joint_name = '次';
                        $joint_num = $next['num'];
                        $joint_type = $next['type'];
                    }
                    if(empty($next) && empty($master)){
                        $list[$k]['joint_table'] = (object) null;
                    }else{
                        $list[$k]['joint_table'] = [
                            'joint_name' => $joint_name,
                            'joint_num' => $joint_num,
                            'joint_type' => $joint_type,
                        ];
                    }

                    $list[$k]['open_table'] =
                        [
                            'status' => 1,
                            'member_id' => $ot['member_id'],
                            'is_fit' => $ot['is_fit'],
                            'open_table_id'=>$ot['open_table_id'],
                            'dinner_num'=>$ot['dinner_num'],
                            'need_pay'=>isset($order['need_pay'])?$order['need_pay']:0,
                            'pay_money'=>$pay_money,
                            'un_pay_money'=>$un_pay_money,
                            'youhui_price'=>$youhui_price,
                            'order_id'=>isset($order['order_id'])?$order['order_id']:0,
                        ]
                    ;
                }else{
                    $list[$k]['open_table'] = $list[$k]['joint_table'] = (object) null;

                }

            }
        }
        return compact('count','list');
    }
    public static function up($data,$where){
        $data['edit_time']=date('Y-m-d H:i:s');
        $res=self::update($data,$where);
        return $res;
    }
    public function qrcode($where){
        $OpenPlatformMiniappHelper = new OpenPlatformMiniappHelper();
        $list=$this->where($where)->select()->toArray();
        if(!empty($list)){
            foreach ($list as &$v){
                $is_create=false;
                if($v['qrcode']==''){
                    $is_create=true;
                }else{
                    $path= root_path().'/public/'.$v['qrcode'];
                    if(file_exists($path) && $v['is_delete']==1){
                        unlink($path);
                    }elseif(!file_exists($path) && $v['is_delete']==0){
                        $is_create=true;
                    }
                }
                if($is_create){
                    $path="pages/home/store/scanFood/dinersNum?shop_id={$v['shop_id']}&table_id={$v['id']}";
                    $img=$OpenPlatformMiniappHelper->setShopId(35)->getQrcode($path);
                    $path1=root_path()."public/upload/tableqrcode/{$v['shop_id']}";
                    if (!is_dir($path1)) {
                        mkdir($path1, 0755, true);
                    }
                    $file_name="upload/tableqrcode/{$v['shop_id']}/".$v['name'].".png";
                    $file_path=root_path().'/public/'.$file_name;
                    file_put_contents($file_path,$img);
                    $v['qrcode']=$file_name;
                    self::up(['qrcode'=>$file_name],['id'=>$v['id']]);
                }
            }
        }
        $folderPath=root_path()."public/upload/tableqrcode/{$where['shop_id']}";
        $zip_path=root_path()."public/upload/tableqrcode/{$where['shop_id']}/{$where['shop_id']}.zip";
        unlink($zip_path);
        $res=$this->zipfile($folderPath,$zip_path);
        $zip_url=$_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST']."/upload/tableqrcode/{$where['shop_id']}/{$where['shop_id']}.zip";
        return ['zip_url'=>$zip_url];
    }
    public function zipfile($folderPath, $zipFilePath) {
        $command = " cd /$folderPath && zip -r {$zipFilePath} ./";
        exec($command, $output, $returnValue);
        return ($returnValue === 0);
    }

}

